package com.example.cupid.service.Impl;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.example.cupid.service.PayService;
import com.example.cupid.util.OrderUtil;
import net.minidev.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;

/**
 * 2021/9/6
 **/
@Service
public class PayServiceImpl implements PayService {
    //应用id
    @Value("${alipay.appId}")
    private String appId;

    //私钥
    @Value("${alipay.privateKey}")
    private String privateKey;

    //公钥
    @Value("${alipay.publicKey}")
    private String publicKey;

    //支付宝网关
    @Value("${alipay.gateway}")
    private String gateway;

    //支付成功后的接口回调地址，不是回调的友好页面，不要弄混了
    @Value("${alipay.notifyUrl}")
    private String notifyUrl;

    @Value("${alipay.returnUrl}")
    private String returnUrl;

    @Value("${alipay.takeNotifyUrl}")
    private String takeNotifyUrl;

    public Object savePay(String msg) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient(gateway,appId,privateKey,
                "json","UTF-8",publicKey,"RSA2");
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(notifyUrl);
        request.setReturnUrl(returnUrl);
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", OrderUtil.getOrderNo());
        bizContent.put("total_amount", 1.11);
        bizContent.put("subject", "高校丘比特订单");
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        String passback_params = URLEncoder.encode(msg, "UTF-8");
        bizContent.put("passback_params",passback_params);
        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        return response.getBody();
    }
    public Object takePay(String msg) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient(gateway,appId,privateKey,
                "json","UTF-8",publicKey,"RSA2");
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(takeNotifyUrl);
        request.setReturnUrl(returnUrl);
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", OrderUtil.getOrderNo());
        bizContent.put("total_amount", 1.11);
        bizContent.put("subject", "高校丘比特订单");
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        String passback_params = URLEncoder.encode(msg, "UTF-8");
        bizContent.put("passback_params",passback_params);
        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        return response.getBody();
    }
}
